package com.snack.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.log4j.Logger;

public class URLUtils {
	private static final Logger logger = Logger.getLogger(URLUtils.class.getName());

	public static String encode(String data, String charset) {
		try {
			return URLEncoder.encode(data, charset);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public static String decode(String data, String charset) {
		try {
			return URLDecoder.decode(data, charset);
		} catch (UnsupportedEncodingException e) {
			logger.warn(e.getMessage(),e);
			throw new RuntimeException(e);
		}
	}

	public static String buildQueryString(Map<String, String> map, String charset) {
		if (map == null || map.isEmpty())
			return "";
		StringBuilder sb = new StringBuilder();
		int i = 0;

		for (Map.Entry<String, String> entry : map.entrySet()) {
			if (i > 0) {
				sb.append("&");
			}
			sb.append(entry.getKey());
			sb.append("=");
			sb.append(encode(entry.getValue(), charset));
			i++;
		}

		return sb.toString();
	}
}
